package alogrithm;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/18 10:46
 */
public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n < 1) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && n > 0) {
            n--;
            fast = fast.next;
        }
        if (fast == null) {
            return head.next;
        }
        while (fast != null) {

            fast = fast.next;
            slow = slow.next;

        }
        slow.next = slow.next.next;
        return head;
        /*// write code here
        if (head == null) {
            return head;
        }
        ListNode dummyNode = new ListNode(0);
        ListNode tmp = head;
        int len = 0;
        while (tmp != null) {
            len++;
            tmp = tmp.next;
        }
        dummyNode.next = head;
        ListNode pre = null;
        ListNode cur = dummyNode;
        len -= n;
        while (cur.next != null && len > 0) {
            len--;
            pre = cur;
            cur = cur.next;
        }
        pre.next = cur.next;
        return dummyNode.next;*/
    }

    public class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
}
